package com.zjj.reggie.filter;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zjj.reggie.common.BaseContext;
import com.zjj.reggie.common.R;
import com.zjj.reggie.entity.Employee;
import com.zjj.reggie.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@Slf4j//日志注解
@WebFilter(filterName = "LoginCheckFilter" ,urlPatterns = "/*")//拦截所有请求
/**
 * 登录检查过滤器
 */
public class LoginCheckFilter implements Filter {
    //路径匹配器，用于判断请求url是否匹配
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();
    //员工服务
    private EmployeeService employeeService;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // TODO: 登录检查逻辑

        HttpServletRequest request = (HttpServletRequest) servletRequest;//强转ues为HttpServletReqt
        HttpServletResponse response = (HttpServletResponse) servletResponse;//强转为HttpServletResponse

        //获取本次请求的url
        String requestURI = request.getRequestURI();

        log.info("拦截到请求url："+requestURI);
        //定义不用处理的url
        String[] urls =new String[] {
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/common/**",
                "/user/login",//移动端登录接口
                "/user/sendMsg"//发送短信验证码接口
        };

        //判断请求是否需要拦截
        boolean check = check(urls, requestURI);

        if (check) {
            log.info("请求{}不需要拦截：",requestURI);
            filterChain.doFilter(request, response);//放行请求
            return;
        }
        Long empId = (Long)request.getSession().getAttribute("employee");


    if (empId != null ) {
        //已登录，直接放行
        log.info("用户已登录，用户id 为："+ empId);

        BaseContext.setCurrentId(empId);

        long id = Thread.currentThread().getId();
        log.info("当前线程id为："+id);


        filterChain.doFilter(request, response);//放行请求
        return;
        //判断移动端用户是否登录
    }
        //判断管理端用户是否登录
        Long userId = (Long)request.getSession().getAttribute("user");
        if ( userId != null  ) {
            //已登录，直接放行
            log.info("用户已登录，用户id 为："+ userId);


            BaseContext.setCurrentId(userId);


            filterChain.doFilter(request, response);
            return;
        }

        log.info("用户未登录");
        //未登录，用输出流方式向客户端页面响应数据
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;
    }

    /**
     * 判断请求是否需要拦截
     * @param urls 不用处理的url
     * @param requestURI 本次请求的url
     * @return true：需要拦截；false：不需要拦截
     */
    private boolean check(String[] urls, String requestURI) {
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, requestURI);
            if (match) {
                return true;
            }
        }
        return false;
    }
}
